package cn.minsh.lims.eoms.modules.app.controller;

import cn.minsh.lims.eoms.common.utils.PageUtils;
import cn.minsh.lims.eoms.common.utils.R;
import cn.minsh.lims.eoms.modules.app.controller.req.*;
import cn.minsh.lims.eoms.modules.app.controller.res.MaintenanceOrderInfoRes;
import cn.minsh.lims.eoms.modules.app.controller.res.MaintenanceOrderListRes;
import cn.minsh.lims.eoms.modules.app.entity.MaintenanceOrderEntity;
import cn.minsh.lims.eoms.modules.app.enums.OrderStatusEnum;
import cn.minsh.lims.eoms.modules.app.enums.OrderTypeEnum;
import cn.minsh.lims.eoms.modules.app.service.MaintenanceOrderService;
import cn.minsh.lims.eoms.modules.app.utils.ErrorMessageUtils;
import cn.minsh.lims.eoms.common.utils.ParamUtils;
import cn.minsh.lims.eoms.modules.app.utils.UserUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.util.Date;
import java.util.Objects;


/**
 * 保养工单
 *
 * @author lht
 * @email sunlightcs@gmail.com
 * @date 2021-04-30 00:17:00
 */
@RestController
@RequestMapping("sys/maintenanceOrder")
@Api(tags = "保养工单（优化级别-》类型）")
public class MaintenanceOrderController {
    @Autowired
    private MaintenanceOrderService maintenanceOrderService;

    /**
     * 列表
     */
    @PostMapping("/list")
    @ApiOperation("保养工单列表")
    @ApiResponses({
            @ApiResponse(code = 200,message = "ok",response = MaintenanceOrderListRes.class)
    })
    public R list(@RequestBody MaintenanceOrderListReq req,
                  HttpServletRequest request){
        PageUtils page = maintenanceOrderService.queryPage(req,UserUtils.getUserId(request));

        return R.ok().put("data", page);
    }


    /**
     * 信息
     */
    @GetMapping("/info/{id}")
    @ApiOperation("保养工单详情")
    @ApiResponses({
            @ApiResponse(code = 200,message = "ok",response = MaintenanceOrderInfoRes.class)
    })
    public R info(@PathVariable("id") Long id,HttpServletRequest request){
        MaintenanceOrderInfoRes res = maintenanceOrderService.queryById(id,UserUtils.getUserId(request));

        return R.ok().put("data", res);
    }

    /**
     * 保存
     */
    @PostMapping("/save")
    @ApiOperation("添加保养工单")
    public R save(@RequestBody @Valid MaintenanceOrderReq req,
            BindingResult bindingResult,
                  HttpServletRequest request){
        try {
            ParamUtils.check(bindingResult);
            //如果委外保养，供应商必填
            if (OrderTypeEnum.OUTSOURCING.getCode().equals(req.getType())
                    && (req.getSupplierId()==null || req.getSupplierId()<1)){
                return R.error(ErrorMessageUtils.NOT_BLANK_SUPPLIER) ;
            }
            maintenanceOrderService.saveOrder(req,UserUtils.getUserId(request));
            return R.ok();
        }catch (Exception e){
            return R.error(e.getMessage()) ;
        }

    }

    /**
     * 修改
     */
    @PutMapping("/update")
    @ApiOperation("修改工单")
    public R update(@RequestBody @Valid MaintenanceOrderReq req,BindingResult bindingResult,HttpServletRequest request){
        try {
            ParamUtils.check(bindingResult);
            //如果委外保养，供应商必填
            if (OrderTypeEnum.OUTSOURCING.getCode().equals(req.getType())
                    && (req.getSupplierId()==null || req.getSupplierId()<1)){
                return R.error(ErrorMessageUtils.NOT_BLANK_SUPPLIER) ;
            }

            maintenanceOrderService.updateOrderById(req,UserUtils.getUserId(request));
            return R.ok();
        }catch (Exception e){
            return R.error(e.getMessage()) ;
        }
    }

    /**
     * 删除
     */
    @DeleteMapping("/delete")
    @ApiOperation("删除工单")
    public R delete(@RequestParam("id") Long id,
                    HttpServletRequest request){
        //验证存在
        MaintenanceOrderEntity orderEntity = maintenanceOrderService.getById(id) ;
		if (Objects.isNull(orderEntity) || orderEntity.getId() == null){
		    return R.error("记录不存在") ;
        }

		if (!OrderStatusEnum.NOT_STARTED.getCode().equals(orderEntity.getStatus())){
            return R.error("仅未开始状态工单可删除") ;
        }
		orderEntity.setIsDel(1);
		orderEntity.setUpdateBy(UserUtils.getUserId(request));
        orderEntity.setUpdateTime(new Date());
		maintenanceOrderService.updateById(orderEntity) ;
        return R.ok();
    }

    @PutMapping("/accept")
    @ApiOperation("接受工单")
    public R accept(@RequestBody @Valid AcceptOrderReq req,BindingResult bindingResult,HttpServletRequest request){
        try {
            ParamUtils.check(bindingResult);
            maintenanceOrderService.accept(req,UserUtils.getUserId(request)) ;
            return R.ok();
        }catch (Exception e){
            return R.error(e.getMessage()) ;
        }
    }
    @PutMapping("/reject")
    @ApiOperation("拒绝工单")
    public R reject(@RequestBody @Valid RejectOrderReq req,BindingResult bindingResult,HttpServletRequest request){
        try {
            ParamUtils.check(bindingResult);
            maintenanceOrderService.reject(req,UserUtils.getUserId(request)) ;
            return R.ok();
        }catch (Exception e){
            return R.error(e.getMessage()) ;
        }
    }

    @PutMapping("modifyAgent")
    @ApiOperation("修改经办人")
    public R modifyAgent(@RequestBody @Valid ModifyAgentOrderReq req,BindingResult bindingResult,HttpServletRequest request){
        try {
            ParamUtils.check(bindingResult);
            maintenanceOrderService.updateAgent(req,UserUtils.getUserId(request)) ;
            return R.ok() ;
        }catch (Exception e){
            return R.error(e.getMessage()) ;
        }
    }

    @PutMapping("uploadResult")
    @ApiOperation("上传保养结果")
    public R uploadResult(@RequestBody @Valid MaintenanceResultReq req,BindingResult bindingResult ,HttpServletRequest request){
        try {
            ParamUtils.check(bindingResult);
            maintenanceOrderService.uploadResult(req,UserUtils.getUserId(request)) ;
            return R.ok() ;
        }catch (Exception e){
            return R.error(e.getMessage()) ;
        }
    }

    @PutMapping("closeOrder")
    @ApiOperation("关闭工单")
    public R closeOrder(@RequestBody @Valid MaintenanceOrderCloseReq req,BindingResult bindingResult,HttpServletRequest request){
        try {
            ParamUtils.check(bindingResult);
            maintenanceOrderService.closeOrder(req,UserUtils.getUserId(request)) ;
            return R.ok() ;
        }catch (Exception e){
            return R.error(e.getMessage()) ;
        }
    }

}
